package com.yzt.zhuju.utils;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.alibaba.android.arouter.launcher.ARouter;
import com.yzt.zhuju.IService.message.IMessageService;
import com.yzt.zhuju.R;
import com.yzt.zhuju.broadcast.NotifyBroadCastReceiver;

import static android.app.Notification.VISIBILITY_SECRET;

/**
 * author : bob
 * date   : 2022/12/2
 * desc   :
 */
public class NotificationUtils extends ContextWrapper {

    public static final int REQUEST_SETTING_NOTIFICATION = 1001;

    public void cancelAll() {
        getManager().cancelAll();
    }

    public enum MsgChannel {

        /**
         * MsgChannel
         */
        CHAT("chat_channel", "聊天通知消息", "聊天通知消息渠道"),
        OTHER("other_channel", "其它通知消息", "其它通知消息渠道");

        private final String CHANNEL_ID;

        private final String CHANNEL_NAME;

        private final String CHANNEL_DESCRIPTION;

        /**
         * 构造方法
         */
        MsgChannel(String channelId, String channelName, String channelDescription) {
            this.CHANNEL_ID = channelId;
            this.CHANNEL_NAME = channelName;
            this.CHANNEL_DESCRIPTION = channelDescription;
        }
    }

    private NotificationManager mManager;

    private final MsgChannel msgChannel;

    private final Context context;

    public NotificationUtils(Context base) {
        this(base, MsgChannel.CHAT);
    }

    public NotificationUtils(Context base, MsgChannel msgChannel) {
        super(base);
        this.context = base;
        this.msgChannel = msgChannel;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
        }
    }

    /**
     * 构建通知通道
     */
    private void createNotificationChannel() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(msgChannel.CHANNEL_ID, msgChannel.CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            if (msgChannel == MsgChannel.CHAT) {
                channel = new NotificationChannel(msgChannel.CHANNEL_ID, msgChannel.CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            }

            channel.setDescription(msgChannel.CHANNEL_DESCRIPTION);
            //是否绕过请勿打扰模式
            channel.canBypassDnd();
            //闪光灯
            channel.enableLights(true);
            //锁屏显示通知
            channel.setLockscreenVisibility(VISIBILITY_SECRET);
            //闪关灯的灯光颜色
            channel.setLightColor(Color.RED);
            //桌面launcher的消息角标
            channel.canShowBadge();
            //是否在久按桌面图标时显示此渠道的通知
            channel.setShowBadge(true);
            //是否允许震动
            channel.enableVibration(true);
            //获取系统通知响铃声音的配置
            channel.getAudioAttributes();
            //获取通知取到组
            channel.getGroup();
            //设置可绕过  请勿打扰模式
            channel.setBypassDnd(true);
            //设置震动模式
            channel.setVibrationPattern(new long[]{100, 100, 200});
            //是否会有灯光
            channel.shouldShowLights();

            getManager().createNotificationChannel(channel);
        }
    }

    private NotificationManager getManager() {
        if (mManager == null) {
            mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return mManager;
    }

    /**
     * 取消通知栏
     */
    public static void cancel(Context context, int notifyId) {
        NotificationManager mManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mManager.cancel(notifyId);
    }

    /**
     * 取消通知栏
     */
    public void cancel(int notifyId) {
        getManager().cancel(notifyId);
    }

    private NotificationCompat.Builder getNotification(String title, String content) {
        NotificationCompat.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new NotificationCompat.Builder(getApplicationContext(), msgChannel.CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(getApplicationContext());
            //设置优先级
            builder.setPriority(NotificationCompat.PRIORITY_HIGH);
        }
        //标题
        builder.setContentTitle(title);
        //文本内容
        builder.setContentText(content);
        //小图标
        builder.setSmallIcon(R.mipmap.logo);
        //大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo));
        //设置为一个正在进行的通知，此时用户无法清除通知
//        builder.setOngoing(true);
        //设置消息的提醒方式，震动提醒：DEFAULT_VIBRATE     声音提醒：NotificationCompat.DEFAULT_SOUND
        //三色灯提醒NotificationCompat.DEFAULT_LIGHTS     以上三种方式一起：DEFAULT_ALL
        if (PreferencesUtils.getNotifyVoice()) {
            builder.setDefaults(NotificationCompat.DEFAULT_SOUND);
        }
        //设置震动方式，延迟零秒，震动一秒，延迟一秒、震动一秒
        if (PreferencesUtils.getNotifyVibrate()) {
            builder.setVibrate(new long[]{0, 1000, 1000, 1000});
        }
        //设置点击信息后自动清除通知
        builder.setAutoCancel(true);
        return builder;
    }

    private PendingIntent createIntent(Intent intent) {
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    }

    /**
     * 发送通知
     */
    public void sendNotification(String title, String content) {
        sendNotification(1, title, content);
    }

    /**
     * 发送通知
     */
    public void sendNotification(String title, String content, Intent intent) {
        sendNotification(1, title, content, intent);
    }

    /**
     * 发送通知
     */
    public void sendNotification(String title, String content, PendingIntent intent) {
        sendNotification(1, title, content, intent);
    }

    /**
     * 发送通知
     */
    public void sendNotification(int notifyId, String title, String content) {
        Intent intent = new Intent();
        intent.setClass(context, NotifyBroadCastReceiver.class);
        sendNotification(notifyId, title, content, intent);
    }

    /**
     * 发送通知
     */
    public void sendNotification(int notifyId, String title, String content, Intent intent) {
        NotificationCompat.Builder builder = getNotification(title, content);
        if (intent != null) {
            builder.setContentIntent(createIntent(intent));
        }
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        getManager().notify(notifyId, builder.build());
    }

    /**
     * 发送通知
     */
    public void sendNotification(int notifyId, String title, String content, PendingIntent intent) {
        NotificationCompat.Builder builder = getNotification(title, content);
        if (intent != null) {
            builder.setContentIntent(intent);
        }
        getManager().notify(notifyId, builder.build());
    }

    public NotificationCompat.Builder getNotificationBuild(String title, String content) {
        return getNotification(title, content);
    }

    public void sendNotification(int notifyId, NotificationCompat.Builder builder) {
        getManager().notify(notifyId, builder.build());
    }

    public static void turnToSystemSetting(Activity context) {
        gotoNotificationSetting(context);
    }

    public static void gotoNotificationSetting(Activity activity) {
        ApplicationInfo appInfo = activity.getApplicationInfo();
        String pkg = activity.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        NotificationManager nm = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
        boolean areNotificationsEnabled = NotificationManagerCompat.from(activity).areNotificationsEnabled();
        if (!areNotificationsEnabled) {
            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, pkg);
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, uid);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                intent.putExtra("app_package", pkg);
                intent.putExtra("app_uid", uid);
            } else {
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + pkg));
            }
            activity.startActivityForResult(intent, REQUEST_SETTING_NOTIFICATION);
            return;
        }
        try {
            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                IMessageService messageService = ARouter.getInstance().navigation(IMessageService.class);
                NotificationChannel channel = messageService.getMessageNotificationChannel();
                if (nm.getNotificationChannel(channel.getId()) == null) {
                    nm.createNotificationChannel(channel);
                }
                intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, pkg);
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.getId());
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                intent.putExtra("app_package", pkg);
                intent.putExtra("app_uid", uid);
            } else {
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + pkg));
            }
            activity.startActivityForResult(intent, REQUEST_SETTING_NOTIFICATION);
        } catch (Exception e) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            activity.startActivityForResult(intent, REQUEST_SETTING_NOTIFICATION);
        }
    }

}
